package cn.doitedu.doitedu_eagle.web_server.service;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/***
 * @author hunter.d
 * @qq 657270652
 * @wx haitao-duan
 * @date 2021/3/20
 **/
public class FreemarkerDemo {
    public static void main(String[] args) throws Exception {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File("web_server/src/main/resources/templates/"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        Map root = new HashMap();
        root.put("user", "Big Joe");

        Map animal1 = new HashMap();
        animal1.put("name", "kitty");
        animal1.put("price", "88.6");

        Map animal2 = new HashMap();
        animal2.put("name", "brown");
        animal2.put("price", "66.8");

        ArrayList<Map<String, String>> animals = new ArrayList<>();
        animals.add(animal1);
        animals.add(animal2);

        root.put("animals", animals);

        /* Get the template (uses cache internally) */
        Template temp = cfg.getTemplate("demo.ftl");

        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);
    }
}
